package pers.qianyu.month_202012.date_20201213;

import org.junit.*;

import java.util.*;

/**
 * 84. 柱状图中最大的矩形
 * https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
 *
 * @author mizzle rain
 * @date 2020-12-13 15:15
 */
public class LargestRectangleArea {
    /**
     * 哨兵优化
     */
    public int largestRectangleArea(int[] heights) {
        int len = heights.length;
        if (len == 0) {
            return 0;
        }
        if (1 == len) {
            return heights[0];
        }
        int[] arr = new int[len + 2];
        System.arraycopy(heights, 0, arr, 1, heights.length);
        heights = arr;

        int area = 0;
        Deque<Integer> stack = new LinkedList<>();
        stack.push(heights[0]);
        for (int i = 1; i < heights.length; i++) {
            while (heights[i] < heights[stack.peek()]) {
                int h = heights[stack.pop()];
                int w = i - stack.peek() - 1;
                area = Math.max(w * h, area);
            }
            stack.push(i);
        }
        return area;
    }

    @Test
    public void test1() {
        int[] arr = {2, 1, 5, 6, 2, 3};
        int result = new LargestRectangleArea()
                .largestRectangleArea(arr);
        System.out.println("result = " + result);
    }
}
